'''Contains all the functions used by both HP claim GUIs.'''
import os
from re import match as re_match, sub as re_sub
from logging import (
    basicConfig as logging_basic_config,
    getLogger as logging_get_logger,
    ERROR as logging_error
)
import PySimpleGUI as sg


# To provide consistent coloring for all submit and cancel buttons
SUBMIT_COLOR = ('black', '#55b54c')
VIEW_COLOR = ('black', '#ffd700')
CANCEL_COLOR = ('white', '#ff4040')

# To provide consistent sizing for all text labels and input fields
TEXT_LABEL_SIZE = (16, 1)
TEXT_INPUT_SIZE = (25, 1)


def get_logger(gui_name):
    '''Catches any errors raised by the program, without crashing it.'''
    logging_basic_config(
        level=logging_error,
        filename=f'{gui_name}.log',
        filemode='w',
        format='%(name)s - %(levelname)s - %(message)s'
    )
    return logging_get_logger(__name__)


def validate_claim_info(claim_info):
    '''Ensures all the form fields have values.'''
    for k, v in claim_info.items():
        # Part Numbers and Notes
        if isinstance(v, set):
            if len(v) == 0:
                sg.popup_error(
                    f"You must enter at least one {re_sub('s', '', k)}!",
                    title='Error Message'
                )
                return False
        # Text Inputs
        elif not re_match(r'\w+', v):
            if k == 'po number':
                field_title = 'PO Number'
            elif k == 'learner id':
                field_title = 'HP Learner ID'
            else:
                field_title = k.title()

            sg.popup_error(
                f'You must provide a value for the "{field_title}" field!',
                title='Error Message'
            )
            return False
        else:
            continue

    return True


def choose_note_type():
    '''Specifies the type of note to add to the HP CSN warranty claim.'''
    sg.theme('Reddit')

    layout = [
        [sg.Text('Do you want to enter a Chromebook or non-Chromebook note?')],
        [
            sg.Button(
                'Chromebook',
                key='-CHROMEBOOK-',
                button_color=('white', '#325aff')
            ),
            sg.Button(
                'Non-Chromebook',
                key='-NON_CHROMEBOOK-',
                button_color=('black', '#ffd732')
            )
        ]
    ]

    window = sg.Window('Note Type Selector', layout)
    event = window.read()[0]
    window.close()

    if event == '-CHROMEBOOK-':
        return 'Chromebook'
    elif event == '-NON_CHROMEBOOK-':
        return 'Non-Chromebook'


def get_file_path(file_type):
    '''Gets the absolute path to the specified file.'''
    file_path = sg.popup_get_file(
        f'Please enter the absolute path to the {file_type} file:', title=file_type
    )

    if file_path and os.path.isfile(file_path):
        return file_path


def get_save_folder():
    '''Gets the absolute path to a folder, in order to save a file.'''
    folder_path = sg.popup_get_folder(
        'In which folder would you like to save the file?', title='Save File'
    )

    if folder_path and os.path.isdir(folder_path):
        return folder_path
